<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>lastPromise</title>
  <style>
    .active {
      color: #ff9032;
    }
    #content {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="a-wrap">
      <a href="javascript:;" class="active">全部</a>
      <a href="javascript:;">类型1</a>
      <a href="javascript:;">类型2</a>
    </div>
    <div id="content"></div>
  </div>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script type="module">
    axios.defaults.baseURL = 'http://localhost:9090'

    /* 未限制
     -------------------------------------------------------------------------------- */
    const getContent = params => {
      return axios({
        url: '/content',
        params
      })
    }

    /* 方案一：借助 axios 的 CancelToken
     -------------------------------------------------------------------------------- */
    // import { lastPromise } from "./js/cancelToken.js";
    // const getContent = lastPromise((params, source) => {
    //   return axios({
    //     url: '/content',
    //     params,
    //     cancelToken: source.token
    //   })
    // })

    /* 方案二：利用 Promise.race
     -------------------------------------------------------------------------------- */
    // import { lastPromise } from "./js/race.js";
    // const getContent = lastPromise(params => {
    //   return axios({
    //     url: '/content',
    //     params
    //   })
    // })
    
    /* -
     -------------------------------------------------------------------------------- */
    const handleGetContent = params => {
      const contentEl =  document.querySelector('#content')
      contentEl.innerText = '加载中...'
      return getContent(params).then(res => {
        contentEl.innerText = res.data
        return res
      })
    }
    handleGetContent({ type: '全部' })

    const aWrapEl = document.querySelector('.a-wrap')
    aWrapEl.addEventListener('click', function (e) {
      if(e.target.tagName === 'A') {
        for (let i = 0; i < aWrapEl.children.length; i++) {
          const el = aWrapEl.children[i];
          el.classList.remove('active')
        }
        e.target.classList.add('active')
        handleGetContent({ type: e.target.innerText })
      }
    })
    
  </script>
</body>
</html>